const PENDING = 'pending'; // 等待
const FULLFILLED = 'fullfilled'; // 成功
const REJECTED = 'rejected'; // 失败
class MyPromise {
  // 立即执行
  constructor (executor) {
    // 错误处理，失败之后立即返回
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }
  // Promise 状态
  status = PENDING
  // 成功之后的值
  value = undefined
  // 失败之后的原因
  reason = undefined
  // 成功
  successCallback = []
  // 失败
  failCallback = []
  resolve = value => {
    // 如果状态不是等待，阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态更改为成功
    this.status = FULLFILLED
    // 保存成功之后的值
    this.value = value
    // 判断成功回调是否存在，如果存在调用
    while (this.successCallback.length) {
      this.successCallback.shift()()
    }
  }
  reject = reason => {
    // 如果状态不是等待，阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态更改为失败
    this.status = REJECTED
    // 保存失败之后的原因
    this.reason = reason
    // 判断失败回调是否存在，如果存在调用
    // this.failCallback && this.failCallback(this.reason)
    while (this.failCallback.length) {
      this.failCallback.shift()()
    }
  }

  then (successCallback, failCallback) {
    // 这里判断 调用then()没有传值，值也需要一直往下传
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULLFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 等待
        // 将失败和成功的回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        }) 
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason)
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise2
  }

  finally (callback) {
    // then之后还可以调用then，所以这里直接返回一个then
    return this.then((value) => {
      return MyPromise.resolve(callback().then(() => value))
    }, (reason) => {
      return MyPromise.resolve(callback().then(() => {throw reason}))
    })
  }

  catch (failCallback) {
    return this.then(undefined, failCallback)
  }

  static all (array) {
    let result = []
    let index = 0
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        // 异步处理，当array的长度和index相等的时候，表明函数已经全部执行
        if (index === array.length) {
          console.log(index === array.length)
          resolve(result)
        }
      }
      for (let i =0; i< array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // promise 对象
          current.then(value => addData(i, value), reason => { reject(reason) })
        } else {
          // 普通值
          addData(i, array[i])
        }
      }
    })
  }

  // 静态对象, 直接调用resolve，将给定的值转换为promise对象
  static resolve (value) {
    if (value instanceof MyPromise) {
      // 如果是promise对象直接返回
      return value
    } else {
      // 不是promose 新建一个promise返回
      return new MyPromise(resolve => {
        resolve(value)
      })
    }
  }
}


/* 
  处理then中返回Promise的情况
  1. 判断X的值是普通对象还是Promise 值
  2. 如果是普通值，直接resolve
  3. 如果是Promise, 查看Promise 返回的结果
  4. 再根据Promise 返回的结果，决定调用resolve还是reject
*/
function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('不能循环调用promise'))
  }
  if (x instanceof MyPromise) {
    // Promise
    // x.then(value => resolve(value), reason => reject(reason))
    x.then(resolve, reject)
  } else { 
    // 普通对象
    resolve(x)
  }
}

module.exports = MyPromise